import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import rTime from 'dayjs/plugin/relativeTime';
dayjs.locale('zh-cn');
dayjs.extend(rTime);

/**
 * 格式化日期
 * @param date 
 * @param type 
 * @returns 
 */
export function formatDate(date:any, type = 'YYYY年MM月DD日') {
  date = new Date(date).getTime();
  return dayjs(date).format(type);
};

/**
 * 格式化出生日期
 * @param idNumber  身份证号 
 */
export function formatBirthday(idNumber:string = "") {
  if (!idNumber) {
    return '';
  }
  let birthday = "";
  if (idNumber.length === 15) {
    birthday = `19${idNumber.slice(6, 12)}`;
  } else if (idNumber.length === 18) {
    birthday = `${idNumber.slice(6, 14)}`;
  }
  birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');
  return birthday;
}

/**
 * 格式化年
 * @param idNumber  身份证号 
 * @param type      类型（age）
 */
export function formatYear(idNumber:string = "", type:string = "") {
  let year = "";
  const now = new Date();
  if (type === 'age') {
    year = formatBirthday(idNumber);
  }
  return now.getFullYear() - +year.substring(0,4);
}